# encoding=utf-8
from flask import Flask, jsonify, request
from flask_cors import CORS
import sys
import test_api
import time
import service
import json
from multiprocessing import Process, Pool
sys.path.append("../ir/")
sys.path.append("../mysql/")
sys.path.append("../mongo/")
import redis
import search
import search2
import mysql_helper
import mysql_helper2
import mongo_helper2

app = Flask(__name__)
CORS(app, supports_credentials=True)

@app.route("/search_all")
def search_all():
    search_tag = request.values.get("tag")
    #1217
    r = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
    #1217
    pos_num = 0
    neg_num = 0
    search_token = time.asctime(time.localtime(time.time()))
    while True:
        res = r.get(search_tag)
        if res is not None:
            if res == "no_more_ids":
                response = {"has_more_mblog": 0}
                break
            else:

                search_items = r.get("search_items")

                if search_items == "no_regex":
                    regex = False
                else:
                    regex = True
                    search_items = json.loads(search_items)["list"]

                doc_list1 = json.loads(res)["id_list"]
                query = json.loads(res)["query"]
                mblogs1 = mysql_helper2.get_mblog_by_docids(doc_list1)



                resp_mblogs = []

                for index, mblog in enumerate(mblogs1):
                    resp_mblog = {}
                    resp_mblog["user_name"] = mblog[0]
                    sentiment = mblog[5]
                    if sentiment == 1:
                        pos_num += 1
                    elif sentiment == -1:
                        neg_num += 1
                    resp_mblog["sentiment"] = mblog[5]

                    if regex:
                        processed_text = service.process_text_regex(mblog[1], search_items)
                    else:
                        processed_text = service.process_text(mblog[1], query)

                    resp_mblog["text"] = processed_text
                    pic_urls = mblog[2]
                    if pic_urls != '':
                        pic_urls = pic_urls.split(",")
                        if len(pic_urls) > 5:
                            pic_urls = pic_urls[:5]
                        resp_mblog["pic_num"] = len(pic_urls)
                    else:
                        pic_urls = []
                        resp_mblog["pic_num"] = 0
                    resp_mblog["pic_infos"] = pic_urls
                    video_url = mblog[3]
                    if video_url != '':
                        resp_mblog["is_video"] = True
                        processed_url = service.process_video_url(mblog[1])
                        resp_mblog["video_url"] = processed_url if processed_url != "" else mblog[3]
                    else:
                        resp_mblog["is_video"] = False
                        resp_mblog["video_url"] = ''
                    resp_mblog["show_pic"] = False
                    resp_mblog["created_at"] = service.process_standard_time(mblog[4])
                    resp_mblogs.append(resp_mblog)
                r.set(search_token, json.dumps({"mblogs": resp_mblogs}), ex=3600)
                r.set(search_tag + "mblog", json.dumps({"mblogs": resp_mblogs}), ex=3600)
                response = {"pos_num": pos_num, "neg_num": neg_num, "search_token": search_token, "has_more_mblog": 1}
                break
        else:
            time.sleep(0.300)
    return jsonify(response)


@app.route("/search")
def hello_world():

    begin_time = time.time()
    query = request.values.get("query")
    search_tag = request.values.get("tag")

    regex = False
    if "*" in query:
        regex = True
        # 通配符查询
        # 通配符在前面，
        # 通配符在后面
        search_items, doc_list1 = mongo_helper2.get_doc_by_regex(query)
        print(search_items)
        print(len(doc_list1))
    else:
        doc_list1 = search2.search_item(query)

    # 1217
    if len(doc_list1) == 0:
        r = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
        r.set(search_tag, "no_more_ids", ex=3600)
        no_res_time = time.time() - begin_time
        response = {"pos_num": 0, "neg_num": 0, "mblogs": [], "res_num": 0, "total_time": round(no_res_time, 2)}
        return jsonify(response)
    # 1217

    doc_list1 = list(set(doc_list1))
    docids = doc_list1
    total_num = len(doc_list1)
    r = redis.StrictRedis(host='localhost', port=6379, db=0)
    if total_num > 10:
        doc_list1 = doc_list1[:10]

        if regex:
            r.set("search_items", json.dumps({"list": search_items}), ex=3600)
        else:
            r.set("search_items", "no_regex", ex=3600)
    else:
        r = redis.StrictRedis(host='localhost', port=6379, db=0)
        r.set(search_tag, "no_more_ids", ex=3600)
        print("no_more_ids ===  1111")



    print("数据库1查找到{}条".format(total_num))

    mysql_time1 = time.time()
    mblogs1 = mysql_helper2.get_mblog_by_docids(doc_list1)

    if total_num > 10:
        r.set(search_tag, json.dumps({"id_list": docids, "query": query}), ex=3600)

    mysql_time2 = time.time()

    print("mysql查询时间 {} 秒".format(mysql_time2 - mysql_time1))


    resp_mblogs = []
    pos_num = 0
    neg_num = 0

    for index, mblog in  enumerate(mblogs1):
        resp_mblog = {}

        resp_mblog["user_name"] = mblog[0]



        if total_num <= 10:
            sentiment = mblog[5]
            if sentiment == 1:
                pos_num += 1
            elif sentiment == -1:
                neg_num += 1

        resp_mblog["sentiment"] = mblog[5]
        if regex :
            processed_text = service.process_text_regex(mblog[1], search_items)
        else:
            processed_text = service.process_text(mblog[1], query)
        resp_mblog["text"] = processed_text
        pic_urls = mblog[2]
        if pic_urls != '':
            pic_urls = pic_urls.split(",")
            if len(pic_urls) > 5:
                pic_urls = pic_urls[:5]
            resp_mblog["pic_num"] = len(pic_urls)
        else:
            pic_urls = []
            resp_mblog["pic_num"] = 0
        resp_mblog["pic_infos"] = pic_urls
        video_url = mblog[3]
        if video_url != '':
            resp_mblog["is_video"] = True
            processed_url = service.process_video_url(mblog[1])
            resp_mblog["video_url"] = processed_url if processed_url != "" else mblog[3]
        else:
            resp_mblog["is_video"] = False
            resp_mblog["video_url"] = ''
        resp_mblog["show_pic"] = False
        resp_mblog["created_at"] = service.process_standard_time(mblog[4])
        resp_mblogs.append(resp_mblog)


    end_time = time.time()
    total_time = end_time - begin_time

    if total_num <= 10:
        response = {"pos_num": pos_num, "neg_num": neg_num, "mblogs": resp_mblogs}
    else:
        response = {"mblogs": resp_mblogs}
    response["res_num"] = total_num
    response["total_time"] = round(total_time, 2)


    return jsonify(response)

@app.route("/next")
def next():
    search_token = request.values.get("search_token")
    start_index = request.values.get("start_index")

    start_index = int(start_index)
    r = redis.StrictRedis(host='localhost', port=6379, db=0)
    mblogs = r.get(search_token)
    mblogs = json.loads(mblogs)["mblogs"]
    mblogs = mblogs[start_index: start_index + 10]
    response = {"mblogs": mblogs}
    return jsonify(response)

@app.route("/suggestion")
def suggestion():
    query = request.values.get("query")
    res = mongo_helper2.get_suggestion_item(query)
    response = {"suggestion": res}
    return jsonify(response)


@app.route("/senti_changes")
def senti_changes():
    search_tag = request.values.get("tag")
    # 1217
    r = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
    response = {}
    sentiments = []
    sentiments_times = []
    times = []
    n = 0
    while True:
        res = r.get(search_tag)
        if res is not None:
            print("no_more_ids ===  1111", res)
            if res == "no_more_ids":
                response["no_need_senti_change"] = 1
            else:
                response["no_need_senti_change"] = 0
            break
        else:
            time.sleep(0.100)
    if response["no_need_senti_change"] == 1:
        return jsonify(response)
    else:
        while True:
            mblogs = r.get(search_tag+"mblog")

            if mblogs is not None:
                mblogs = json.loads(mblogs)["mblogs"]
                #按照时间排序
                n = len(mblogs)
                for i in range(n - 1):
                    for j in range(n - 1 - i):
                        if mblogs[j].get("created_at") > mblogs[j + 1].get("created_at"):
                            temp = mblogs[j + 1]
                            mblogs[j + 1] = mblogs[j]
                            mblogs[j] = temp

                # 测试一下：
                for i in range(n):
                    if len(sentiments) < 20:
                        sentiments.append(mblogs[i].get("sentiment"))
                        sentiments_times.append(mblogs[i].get("created_at"))
                    else:
                        # 如果负面情绪至少15个，正面最多5个，差>= 10
                        if sum(sentiments) <= -10:
                            times.append([sentiments_times[0], sentiments_times[-1]])
                            sentiments = []
                            sentiments_times = []
                        else:
                            sentiments = sentiments[1:]
                            sentiments_times = sentiments_times[1:]

                break
            else:
                time.sleep(0.100)
    response["times"] = times
    return jsonify(response)



@app.route("/relate")
def relate():
    query = request.values.get("query")
    res = mongo_helper2.get_item(query)
    response = {"relate": res}
    return jsonify(response)

if __name__ == "__main__":
    app.run(host='0.0.0.0')